//
//  WTPrivateMessageView.m
//  WTPlayDemo
//
//  Created by ben on 16/7/25.
//  Copyright © 2016年 ben. All rights reserved.
//

#import "WTPrivateMessageView.h"
#import "Masonry.h"
#import "WTPrivateMessageCell.h"
#import "WTCategories.h"
#import "WTLiveSDK.h"
#import "UIImage+WTExtend.h"



@interface WTPrivateMessageView ()<UITableViewDelegate,UITableViewDataSource,NIMConversationManagerDelegate>
@property (nonatomic, strong) UILabel*      titleLabel;
@property (nonatomic, strong) UIView*       lineView;
@property (nonatomic, strong) UITableView*  messageListTableView;
@property (nonatomic, strong) UIButton*     backButton;
@property (nonatomic, strong) UIView*       chatToolView;
@property (nonatomic, strong) UIButton*     picButton;
@property (nonatomic, strong) UITextField*  inputTextField;

@property (nonatomic, strong) NSMutableArray *  recentSessions;
@property (nonatomic, assign) BOOL              isNoData;
@property (nonatomic, strong) UILabel*          zhuboNoMessageView;
@end

@implementation WTPrivateMessageView
- (instancetype)initWithFrame:(CGRect)frame{

    self = [super initWithFrame:frame];
    if (self) {
        
        self.backgroundColor = [UIColor whiteColor];
        [self setup];
    }
    return self;
}

#pragma mark -
- (void)setup{
    
    self.titleLabel = ({
        
        UILabel* label = [[UILabel alloc] init];
        label.numberOfLines = 1;
        label.textColor = [UIColor hexChangeFloat:@"323232"];
        label.font = [UIFont systemFontOfSize:12];
        label.text = @"我的私信";
        [self addSubview:label];
        label;
    });
    
    
    self.lineView = ({
        UIView* view = [[UIView alloc] init];
        view.backgroundColor = [UIColor hexChangeFloat:@"b6b6b6"];
        [self addSubview:view];
        view;
    });
    
    self.backButton = ({
        
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.alpha = 0;
        [button setImage:[UIImage wt_imageWithName:@"wt_play_privatemessage_back"] forState:UIControlStateNormal];
        [self addSubview:button];
        button;
    });
    
    self.messageListTableView = ({
        
        UITableView* view = [[UITableView alloc] init];
        view.backgroundColor = [UIColor hexChangeFloat:@"f0f0f0"];
        [view registerNib:[UINib nibWithNibName:@"WTPrivateMessageCell" bundle:nil] forCellReuseIdentifier:NSStringFromClass([WTPrivateMessageCell class])];
        view.separatorStyle = UITableViewCellSeparatorStyleNone;
        view.dataSource = self;
        view.delegate = self;
        [self addSubview:view];
        view;
    });
    
    self.chatLetterView = ({
        WTPrivateLetterView* view = [[WTPrivateLetterView alloc] init];
        view.alpha = 0;
        [self addSubview:view];
        view;
    });
    
    self.chatToolView = ({
        UIView* view = [[UIView alloc] init];
        view.alpha = 0;
        view.backgroundColor = [UIColor whiteColor];
        [self addSubview:view];
        view;
    });
    
    self.picButton = ({
        
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"发送" forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:12];
        button.layer.cornerRadius = 8;
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button setBackgroundColor:[UIColor themeColor]];
        button.layer.cornerRadius = 15;
        button.layer.masksToBounds = YES;
        [self.chatToolView addSubview:button];
        button;
    });
    
    
    self.inputTextField = ({
        
        UITextField* field = [[UITextField alloc] init];
        field.backgroundColor = [UIColor hexChangeFloat:@"EDEDED"];
        field.layer.cornerRadius = 8;
        field.layer.masksToBounds = YES;
        [self.chatToolView addSubview:field];
        field;
    });
    
    
    self.zhuboNoMessageView = ({
        
        UILabel* label = [[UILabel alloc] init];
        label.hidden = YES;
        label.backgroundColor = [UIColor hexChangeFloat:@"f0f0f0"];
        label.text = @"暂无消息";
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:12];
        label.textColor = [UIColor hexChangeFloat:@"969696"];
        [self addSubview:label];
        label;
    });
    [self layout];
}


#pragma mark - 
- (void)layout{
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.mas_centerX);
        make.top.mas_equalTo(10);
    }];
    
    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.and.trailing.mas_equalTo(0);
        make.top.mas_equalTo(35);
        make.height.mas_equalTo(1/[UIScreen mainScreen].scale);
    }];
    
    [self.backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(6);
        make.top.mas_equalTo(0);
        make.height.and.width.mas_equalTo(35);
        
    }];
    
    [self.messageListTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.lineView.mas_bottom);
        make.leading.and.trailing.and.bottom.mas_equalTo(0);
    }];
    
    [self.zhuboNoMessageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.messageListTableView);
    }];
    
    [self.chatLetterView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.lineView.mas_bottom);
        make.leading.and.trailing.mas_equalTo(0);
        make.bottom.mas_equalTo(self.chatToolView.mas_top);
    }];
    
    [self.chatToolView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.and.trailing.and.bottom.mas_equalTo(0);
        make.height.mas_equalTo(40);
    }];
    
    
    [self.picButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(-10);
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(54);
        make.centerY.mas_equalTo(self.chatToolView.mas_centerY);
    }];
    
    [self.inputTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(8);
        make.trailing.mas_equalTo(self.picButton.mas_leading).offset(-8);
        make.height.mas_equalTo(30);
        make.centerY.mas_equalTo(self.chatToolView.mas_centerY);
    }];
    
    [self handle];
}


#pragma mark - 
- (void)handle{
    
    [[NIMSDK sharedSDK].conversationManager addDelegate:self];
    
    __weak __typeof(self)weakSelf = self;
    [self.backButton addAction:^{
        
        [UIView animateWithDuration:.25 animations:^{ //点击返回 隐藏返回按钮 和 聊天页面 和底部的聊天框
            weakSelf.chatLetterView.alpha = 0;
            weakSelf.backButton.alpha = 0;
            weakSelf.chatToolView.alpha = 0;
        }];
        
        weakSelf.titleLabel.text = @"我的私信"; //恢复顶部标题的内容
        if([weakSelf.inputTextField isFirstResponder]){
            [weakSelf dismissKeyBoard];
        }
    }];
    
    [self.picButton addAction:^{
        
        if(!weakSelf.inputTextField.text || weakSelf.inputTextField.text.length <= 0){
            [weakSelf showTip:@"消息不可以为空"];
        }else {
            
            NIMMessage* message =  [[WTLiveSDK shareSDK].chatManager sendChatMessage:weakSelf.inputTextField.text sessionID:weakSelf.chatLetterView.private_chat_net_ease];
            WTBaseMessageModel* chatMessageModel = [WTMessageFactory chatMessageModelWithRemoteExt:message.remoteExt];
            chatMessageModel.chat_message_text = message.text;
            chatMessageModel.chat_message_message_id = message.messageId;
            [weakSelf.chatLetterView insertMessages:@[chatMessageModel]];
            weakSelf.inputTextField.text = nil;
        }
    }];
}


#pragma 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    WTPrivateMessageCell* cell = [tableView dequeueReusableCellWithIdentifier:@"WTPrivateMessageCell"];
    
    if(self.isNoData){
        cell.messageLabel.text = @"Hi,我是主播，快来约我聊天吧";
        cell.levelLabel.text = [NSString stringWithFormat:@"%zd",self.anchor_info_model.anchor_level];
        [cell.avatarImageView sd_setImageWithURL:[NSURL URLWithString:self.anchor_info_model.anchor_avatar] placeholderImage:[UIImage wt_imageWithName:@"wt_avatar"]];
        cell.nickLabel.text = self.anchor_info_model.anchor_name;
    }else {

        NIMRecentSession *recent = self.recentSessions[indexPath.row];
        cell.messageLabel.text = recent.lastMessage.text;
        NSDictionary*  messageExt = [recent.lastMessage.remoteExt mj_JSONObject];
        NSString* icon = messageExt[@"avatar"];
        if(!icon){
            icon = messageExt[@"wt_avatar"];
        }
        NSString* name = messageExt[@"name"];
        NSInteger level = [messageExt[@"level"] integerValue];
        [cell.avatarImageView sd_setImageWithURL:[NSURL URLWithString:icon] placeholderImage:[UIImage wt_imageWithName:@"wt_avatar"]];
        cell.nickLabel.text = name;
        cell.levelLabel.text = [NSString stringWithFormat:@"%zd",level];
    }
    
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if(self.isNoData){
        return 1;
    }
    return self.recentSessions.count;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [UIView animateWithDuration:.25 animations:^{ //显示聊天框 和 聊天页面 和 返回按钮
        self.chatLetterView.alpha = 1;
        self.backButton.alpha = 1;
        self.chatToolView.alpha = 1;
    }];
    if(self.isNoData){
        self.titleLabel.text = self.anchor_info_model.anchor_name; //设置对应的聊天的人
    }else {
        NIMRecentSession *recent = self.recentSessions[indexPath.row];
        NSDictionary*  messageExt = [recent.lastMessage.remoteExt mj_JSONObject];
        NSString* name = messageExt[@"name"];
        self.titleLabel.text = name;
        
        NSArray<NIMMessage *> *messages = [[[NIMSDK sharedSDK] conversationManager] messagesInSession:recent.session
                                                                                              message:nil
                                                                                                limit:100];
        self.chatLetterView.private_chat_net_ease = recent.session.sessionId;
        [self.chatLetterView insertLocalMessages:messages];
    }
}

- (void)popKeyBoard{
    [self.inputTextField becomeFirstResponder];
}

- (void)dismissKeyBoard{
    [self.inputTextField resignFirstResponder];
}

- (BOOL)isChatStatus{
    return self.chatLetterView.alpha == 1;
}


- (void)update{
    
    self.recentSessions = [[NIMSDK sharedSDK].conversationManager.allRecentSessions mutableCopy];
    
    if(self.recentSessions && self.recentSessions.count > 0){
        if(!self.is_live){ //观众端 只需要取出和当前主播聊天的会话记录
            
            NSMutableArray* tmp = [NSMutableArray arrayWithCapacity:0];
            [self.recentSessions enumerateObjectsUsingBlock:^(NIMRecentSession*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if([obj.session.sessionId isEqualToString:self.anchor_info_model.anchor_net_ease]){
                    [tmp addObject:obj];
                }
            }];
            self.recentSessions = tmp;
        }
    }
    
    if(self.recentSessions.count <= 0){ //没有会话记录
        
        if(self.is_live){ //主播端
            self.zhuboNoMessageView.hidden = NO;
            self.messageListTableView.hidden = YES;
        }else { //观众端
            self.zhuboNoMessageView.hidden = YES;
            self.messageListTableView.hidden = NO;
            //标记
            self.isNoData = YES;
            
            [self.messageListTableView reloadData];
        }
    }else { //如果有会话记录
        
        self.zhuboNoMessageView.hidden = YES;
        self.messageListTableView.hidden = NO;
        //标记
        self.isNoData = NO;
        
        [self.messageListTableView reloadData];
    }

}

#pragma mark lifecycle
- (void)dealloc{

    [[NIMSDK sharedSDK].conversationManager removeDelegate:self];
}


#pragma mark - NIMConversationManagerDelegate
- (void)didAddRecentSession:(NIMRecentSession *)recentSession
           totalUnreadCount:(NSInteger)totalUnreadCount{
    [self.recentSessions addObject:recentSession];
    [self sort];
    [self update];
}


- (void)didUpdateRecentSession:(NIMRecentSession *)recentSession
              totalUnreadCount:(NSInteger)totalUnreadCount{
    for (NIMRecentSession *recent in self.recentSessions) {
        if ([recentSession.session.sessionId isEqualToString:recent.session.sessionId]) {
            [self.recentSessions removeObject:recent];
            break;
        }
    }
    NSInteger insert = [self findInsertPlace:recentSession];
    [self.recentSessions insertObject:recentSession atIndex:insert];
    [self update];
}

- (NSInteger)findInsertPlace:(NIMRecentSession *)recentSession{
    __block NSUInteger matchIdx = 0;
    __block BOOL find = NO;
    [self.recentSessions enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NIMRecentSession *item = obj;
        if (item.lastMessage.timestamp <= recentSession.lastMessage.timestamp) {
            *stop = YES;
            find  = YES;
            matchIdx = idx;
        }
    }];
    if (find) {
        return matchIdx;
    }else{
        return self.recentSessions.count;
    }
}

- (void)sort{
    
    [self.recentSessions sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NIMRecentSession *item1 = obj1;
        NIMRecentSession *item2 = obj2;
        if (item1.lastMessage.timestamp < item2.lastMessage.timestamp) {
            return NSOrderedDescending;
        }
        if (item1.lastMessage.timestamp > item2.lastMessage.timestamp) {
            return NSOrderedAscending;
        }
        return NSOrderedSame;
    }];
}


@end
